var express = require('express');
var router = express.Router();
const { create, userNameAll, findPassword, changeUser, selectUsers } = require('../models/user')
const { success, fail } = require('../utils/response')
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const svgCaptcha = require('svg-captcha');

// 白名单路由（无需验证）
const WHITE_LIST = [
  '/api/login',
];


// 注册
router.post('/create', async (req, res) => {
  try {
    const { username, password, email } = req.body
    if (!username || !password) {
      return fail(res, '请输入用户名和密码')
    }
    const userNameList = await userNameAll()
    if (userNameList.some(item => item.username === username)) {
      return fail(res, '用户名重复')
    }
    const id = await create(username, password, email)
    success(res, id, '创建成功');
  } catch (error) {
    console.error('用户创建失败:', error);
    fail(res, error)
  }
})

// 登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body
    if (!username || !password) {
      return fail(res, '请输入用户名和密码')
    }
    const userInfo = await findPassword(username)
    if (!userInfo?.username) {
      return fail(res, '用户名不存在')
    }
    const isPasswordValid = await bcrypt.compare(password.toString(), userInfo.password);
    if (!isPasswordValid) {
      return fail(res, '账号或密码错误')
    }

    const token = jwt.sign(
      { userId: userInfo.id, },
      process.env.JWT_SECRET || 'your_secret_key',
      { expiresIn: '1h' }
    );


    success(res, {
      id: userInfo.id,
      username: userInfo.username,
      email: userInfo.email,
      created_at: userInfo.created_at,
      avatar: userInfo.avatar,
      token: token
    }, "登录成功")
  } catch (error) {
    fail(res, "登录失败")
  }
})

// 生成验证码接口
router.get('/captcha', (req, res) => {
  try {
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      ignoreChars: '0o1i', // 排除容易混淆的字符
      noise: 3, // 干扰线条数
      color: true, // 彩色验证码
      background: '#f5f5f5', // 背景色
    });

    const token = jwt.sign(
      {
        captcha: captcha.text.toLowerCase(),
      },
      process.env.JWT_SECRET || 'your_secret_key',
      {
        expiresIn: Math.floor(Date.now() / 1000) + 300 // 5分钟后过期
      }
    );

    success(res, {
      token, // 返回给前端的JWT
      svg: captcha.data
    }, "操作成功")
  } catch (e) {
    fail(res, "操作失败")
  }
});

// 验证验证码接口
router.post('/verify-captcha', (req, res) => {
  try {
    const { captchaId, code } = req.body;
    if (!captchaId || !code) {
      return fail(res, '缺少参数')
    }
    // 2. 验证JWT有效性
    const decoded = jwt.verify(captchaId, process.env.JWT_SECRET || 'your_secret_key');

    // 验证码
    if (decoded.captcha !== code.toLowerCase()) {
      return fail(res, '验证码错误或过期了')
    }
    success(res, true, "验证成功")
  } catch (e) {
    // 5. 错误处理
    if (e instanceof jwt.JsonWebTokenError) {
      return fail(res, '无效的验证码令牌', 401); // JWT 解析失败
    }
    if (e instanceof jwt.TokenExpiredError) {
      return fail(res, '验证码已过期', 401); // JWT 过期
    }
    console.error('验证码验证异常:', e);
    fail(res, '服务器错误', 500); // 其他未知错误
  }
});

// 修改用户信息接口
router.post('/upload', async (req, res) => {
  try {
    const { username, avatar, id } = req.body
    if (!id || !avatar) {
      return fail(res, "id或avatar为空")
    }
    const rowId = await changeUser(username, avatar, id)
    success(res, { 
      id: rowId.id,
      username: rowId.username,
      avatar: rowId.avatar
    },'修改成功')
    
  } catch (error) {
    fail(res, '修改失败')
  }

})

// 查询所有的用户
router.get('/users', async(req, res) => {
  const { page = 1, size = 10 } = req.query
  try {
    const rows = await selectUsers(page, size)
    rows.forEach(item => {
      delete item.password
    })
    success(res, rows, '操作成功')
  }catch(e){
    fail(res, e, '操作失败')
  }
})

router.delete('/delete/:id', async (req, res) => {
  const { id } = req.params
  try {
    const row = await deleteUser(id)
    success(res, row, "操作成功")
  }catch(e) {
    fail(res, "删除失败")
  }
})

module.exports = router;